﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace Tnelab.WebApp
{
    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Property)]
    public class ScriptCodeAttribute:Attribute
    {
        public object? Context { get; set; }
        string _code;
        public string Code 
        { 
            get {
                var code=this._code;
                var matches=Regex.Matches(code, @"[{]{1}Context.[a-zA-Z.]+[}]{1}");
                if (matches.Count() == 0)
                {
                    return code;
                }
                for (var i = 0; i < matches.Count; i++)
                {
                    var val = matches[i].Value;
                    var temps=val.Substring(1,val.Length-2).Split('.');
                    object obj = Context;
                    for (var j = 1; j < temps.Length; j++)
                    {
                        obj= obj.GetType().GetProperty(temps[j]).GetValue(obj);    
                        if(obj == null)
                        {
                            break;
                        }
                    }                    
                    var index = code.IndexOf(val);
                    code = $"{code.Substring(0, index)}{obj}{code.Substring(index + val.Length)}";
                }
                return code;
            }
            private set=>this._code=value;
        }
        public ScriptCodeAttribute(string code)
        {
            this.Code = code;
        }
    }
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
    public class DoNotConvertToScriptAttribute : Attribute
    {

    }
}
